package com.jahe.learn.netty4.customcodec;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Long类型消息的处理器
 * @author: jahe.lai
 * @create: 2020-01-09 12:02
 */
public class MyLongMessageHandler extends SimpleChannelInboundHandler<Long> {


    private static Logger logger = LoggerFactory.getLogger(MyLongMessageHandler.class);

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        // 模拟消息交互。业务逻辑不应该占用IO线程的时间片。
        new Thread(new Runnable() {
            int i = 0;
            @Override
            public void run() {

                while (i < 5) {
                    i++;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ctx.writeAndFlush(System.currentTimeMillis());
                }
            }
        }).start();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        logger.warn("------{}",msg);


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}
